package com.ojoin.ojoin.eb_spider.service.catchdata;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.service.SupplyInventoryService;
import com.ojoin.ojoin.eb_spider.service.SupplyPaymentService;
import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.NumberUtils;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;

/**
 * 
 * 1.未结算金额：结算单管理》未结款结算单 统计规则： 所有记录金额相加
 * 
 * 2.库存金额：验收单管理》采购单入库-退货出库 根据最新未结款结算单获取结算结束日期，然后获取结算结算日期到今天的出入库金额差
 * 
 */


@Service
public class SupplierSFBESTDataCatchServiceImpl extends
		SLDataCatchBaseServiceImpl {
	private Logger log = LoggerFactory
			.getLogger(SupplierSFBESTDataCatchServiceImpl.class);

	// 保存公司基本信息 key name 名字 bankNum 结款账号
	@Autowired
	private SupplyPaymentService paymentService;

	@Autowired
	private SupplyInventoryService inventoryService;

	Map<String, String> map = new HashMap<String, String>();

	@Override
	public boolean LoginByUserInfo(String baseUrl, String username,
			String password) throws Exception {
		if (isCacheLogin()) {
			return true;
		}

		int loginCount = 1;
		// 开始登陆 最多登陆三次（验证码错误情况）
		String loginReturnMess = ""; // 登陆返回信息
		while (loginCount < verifycodeRetryCount) {

			this.getWebDriver().get(baseUrl);

			this.getWebDriver().sendKeys("id", "login_name", username);
			this.getWebDriver().sendKeys("id", "login_pwd", password);

			loginCount++;

			this.verifycode();
			// 记录验证码请求次数

			this.getWebDriver()
					.findElement("css",
							"body  div  div.body  form  ul li.btn.png input")
					.click();

			if (this.getWebDriver().isLogin(
					"http://supplier.sfbest.cn/default/index/")) {
				return true;
			} else {

				try {
					loginReturnMess = this.getWebDriver().getText("css",
							"body  div  div.message");

					if ("您输入的账户名与密码不匹配，请重新输入！".trim().equals(
							loginReturnMess.trim())) {

						LogUtils.info(log,  this.getAssistCatchData().getStartMess()
								.getPlatformUser().getPlatformName()
								+ "-->username"
								+ username
								+ "登陆失败-->输入的账户名与密码不匹配%s");
						break;
					}

				} catch (Exception e) {

				}

			}

		}

		return false;
	}

	// 验证码处理
	public void verifycode() throws Exception {
		LogUtils.info(log,  this.getAssistCatchData().getStartMess().getPlatformUser()
				.getPlatformName()
				+ " 登陆界面包含验证码.");
		WebElement verifyE = this.getWebDriver().findElement("id", "code");

		if (null != verifyE) {

			String code = this.getWebDriver().getVerifyCodeByDMV3(verifyE);
			WebElement verifycode = this.getWebDriver().findElement("id",
					"verifycode");

			this.getWebDriver().clearByJS(verifycode);
			verifycode.sendKeys(code);

			LogUtils.info(log,  this.getAssistCatchData().getStartMess().getPlatformUser()
					.getPlatformName()
					+ "verifyCode->" + code);

		}

	}

	@Override
	public String catchSupplierName() throws BusinessException {
		initCompanyInfomation();
		String name = "";
		if (null != map) {
			name = map.get("name");
		}
		return name;
	}

	@Override
	public BankCardCheck catchSupplierAccount() throws BusinessException {
		 BankCardCheck bcc = new BankCardCheck();
		initCompanyInfomation();
		String bankNum = "";
		if (null != map) {
			bankNum = map.get("bankNum");
		}

		return bcc;
	}

	public Map<String, String> initCompanyInfomation() {

		String contractUrl = "http://supplier.sfbest.cn/supplier/info/";

		this.getWebDriver().get(contractUrl);

		this.getWebDriver().waitForPageLoad();

		WebElement web = this.getWebDriver().findElement("css",
				"#main  div  table");

		WebElement webname = web.findElement(By
				.cssSelector("tr:nth-child(1)  td"));

		WebElement webbankNum = web.findElement(By
				.cssSelector("tr:nth-child(10)  td"));

		String name = webname.getText();
		String bankNum = webbankNum.getText();

		map.put("name", name);
		map.put("bankNum", bankNum);

		return map;
	}

	@Override
	public boolean getUnpayAccountData() throws BusinessException {

		// 获取所有结算单
		Map<String, TbSlSupplyPayment> waitpay =  this.getAssistCatchData().getStartMess()
				.getWaitpay();

		List<TbSlSupplyPayment> payments = new ArrayList<TbSlSupplyPayment>();

		String fiveDayPurchase = "http://supplier.sfbest.cn/settlement/index/";

		this.getWebDriver().get(fiveDayPurchase);

		WebElement web = this.getWebDriver().findElement("id", "flexigrid");

		List<WebElement> trs = web.findElements(By.tagName("tr"));

		if (null != trs && !trs.isEmpty()) {
			Iterator<WebElement> it = trs.iterator();
			while (it.hasNext()) {
				WebElement tr = it.next();
				// LogUtils.info(log,tr.getText());
				TbSlSupplyPayment payment = new TbSlSupplyPayment();
				payment.setPlatformAccountId( this.getAssistCatchData().getStartMess()
						.getPlatformUser().getId());

				try {
					List<WebElement> tds = tr.findElements(By.tagName("td"));
					// LogUtils.info(log,tds.get(6).getText());

					WebElement invoiceid = tds.get(1);
					WebElement webcreatetime = tds.get(0);
					WebElement webendtime = tds.get(3);
					WebElement Invoicetatol = tds.get(6);

					String endtime = webendtime.getText();
					String settlementId = invoiceid.getText();
					String createTime = webcreatetime.getText();
					String amountD = Invoicetatol.getText();
					amountD = amountD.replace(",", "");

					long amount = NumberUtils.getLongAmount(amountD);

					payment.setSettlementId(settlementId);
					payment.setCreateDate(createTime);
					payment.setAmount(amount);
					payment.setSettlementDate(endtime);
					payment.setSettlementState(TbSlSupplyPayment.WAITPAY);

					payments.add(payment);

				} catch (Exception e) {
					if (trs.size() != 1) {
						LogUtils.error(log, e);
					}
				}
			}
		}

		paymentService.removeSettlementCommon(payments, waitpay);
		List<TbSlSupplyPayment> li = paymentService.changeToPay(waitpay);

		 this.getAssistCatchData().getCata().setPayupdate(li);
		 this.getAssistCatchData().getCata().setSettlement(payments);
		return true;

	}

	protected long handleElement2Inv(List<TbSlSupplyInventory> purchases) {

		long result = 0;
		try {
			WebElement web = this.getWebDriver().findElement("id", "flexigrid");

			List<WebElement> trs = this.getWebDriver().findElements(web, "css",
					"tbody tr");

			if (null != trs && !trs.isEmpty()) {
				if (trs.size() == 1) {
					WebElement th = null;
					try {
						th = web.findElement(By.cssSelector("tbody tr th"));
					} catch (Exception e) {
					}
					if (null != th)
						return new BigDecimal(result).longValue();
				}
				for (WebElement tr : trs) {
					TbSlSupplyInventory inventory = new TbSlSupplyInventory();
					inventory.setPlatformAccountId( this.getAssistCatchData().getStartMess()
							.getPlatformUser().getId());

					WebElement invoiceIdE = tr.findElement(By
							.cssSelector("td:nth-child(2) div"));

					WebElement pnumE = tr.findElement(By
							.cssSelector("td:nth-child(3) div"));

					WebElement store_date = tr.findElement(By
							.cssSelector("td:nth-child(11) div"));

					WebElement amountE = tr.findElement(By
							.cssSelector("td:nth-child(7) div"));

					String id = invoiceIdE.getText();

					String pnum = pnumE.getText();

					String time = store_date.getText();

					String amountd = amountE.getText().replace(",", "");

					long amount = NumberUtils.getLongAmount(amountd);

					// this.getLoanStatTotal().setTotalUnsettleInstoreorder(this.getLoanStatTotal().getTotalUnsettleInstoreorder()+amount);

					String key = id + "_" + pnum;
					inventory.setItemId(id);
					inventory.setStoreDate(time);
					inventory.setItemStatus(TbSlSupplyInventory.IN);
					inventory.setTotalCost(amount);
					inventory.setItemKey(key);
					purchases.add(inventory);

				}

			} else {
				return result;
			}
		} catch (Exception e) {
			LogUtils.error(log, "html 元素解析错误");
		}
		return result;
	}

	protected long handleElement2Outv(List<TbSlSupplyInventory> purchases) {

		long result = 0;
		try {
			WebElement web = this.getWebDriver().findElement("id", "flexigrid");

			List<WebElement> trs = web.findElements(By.cssSelector("tbody tr"));

			if (null != trs && !trs.isEmpty()) {
				if (trs.size() == 1) {
					WebElement th = null;
					try {
						th = web.findElement(By.cssSelector("tbody tr th"));
					} catch (Exception e) {
					}
					if (null != th)
						return new BigDecimal(result).longValue();
				}
				for (WebElement tr : trs) {
					TbSlSupplyInventory inventory = new TbSlSupplyInventory();
					inventory.setPlatformAccountId( this.getAssistCatchData().getStartMess()
							.getPlatformUser().getId());

					WebElement invoiceIdE = tr.findElement(By
							.cssSelector("td:nth-child(2) div"));

					WebElement pnumE = tr.findElement(By
							.cssSelector("td:nth-child(3) div"));

					WebElement store_date = tr.findElement(By
							.cssSelector("td:nth-child(11) div"));

					WebElement amountE = tr.findElement(By
							.cssSelector("td:nth-child(7) > div"));

					String id = invoiceIdE.getText();

					String pnum = pnumE.getText();

					String time = store_date.getText();

					String amountd = amountE.getText().replace(",", "");

					// 库存为正，所以加-号
					long amount = -NumberUtils.getLongAmount(amountd);

					String key = id + "_" + pnum;
					inventory.setItemId(id);
					inventory.setStoreDate(time);
					inventory.setItemStatus(TbSlSupplyInventory.OUT);
					inventory.setTotalCost(amount);
					inventory.setItemKey(key);

					purchases.add(inventory);

				}
			} else {
				return result;
			}
		} catch (Exception e) {
			// LogUtils.error(log,"",e);
		}

		return result;
	}

	@Override
	public boolean getInstoreOrderData() throws BusinessException {
		// 送货记录
		// 对账单
		String etime =  this.getAssistCatchData().getStartMess().getStoreInEndTime();

		String starttime =  this.getAssistCatchData().getStartMess().getStoreInStartTime();

		Map<String, TbSlSupplyInventory> map =  this.getAssistCatchData().getStartMess().getStoreIn();

		List<TbSlSupplyInventory> purchases = new ArrayList<TbSlSupplyInventory>();

		this.getWebDriver().get(
				"http://supplier.sfbest.cn/productInOrOutWh/index");
		this.getWebDriver().click("css",
				"#delete_form div div.tDiv div.tDiv2 div div span");

		this.getWebDriver()
				.sendKeys(
						"css",
						"#advanced_search  table  tbody  tr:nth-child(2)  td:nth-child(2)  input:nth-child(1)",
						starttime);
		this.getWebDriver()
				.sendKeys(
						"css",
						"#advanced_search  table  tbody  tr:nth-child(2)  td:nth-child(2)  input:nth-child(2)",
						etime);

		this.getWebDriver()
				.findElement("css", "#check_type option:nth-child(2)").click();

		this.getWebDriver().click("id", "searchButton");

		String webtotal = this
				.getWebDriver()
				.getText("css",
						"#delete_form  div  div.pDiv  div.pDiv2  div:nth-child(5)  span span");

		int total = Integer.valueOf(webtotal.trim());
		int flag = 1;
		while (total >= flag) {
			flag++;
			handleElement2Inv(purchases);

			this.getWebDriver()
					.click("css",
							"#delete_form > div > div.pDiv > div.pDiv2 > div:nth-child(7) > div.pNext.pButton > span");

		}

		inventoryService.removeInventoryCommon(purchases, map);

		 this.getAssistCatchData().getCata().setInstore(purchases);

		return true;
	}

	@Override
	public boolean getOutstoreOrderData() throws BusinessException {
		// 送货记录
		// 对账单

		String etime =  this.getAssistCatchData().getStartMess().getStoreOutEndTime();
		String starttime =  this.getAssistCatchData().getStartMess().getStoreOutStartTime();
		Map<String, TbSlSupplyInventory> map =  this.getAssistCatchData().getStartMess()
				.getStoreOut();

		List<TbSlSupplyInventory> purchases = new ArrayList<TbSlSupplyInventory>();

		this.getWebDriver().get(
				"http://supplier.sfbest.cn/productInOrOutWh/index");
		this.getWebDriver().click("css",
				"#delete_form div div.tDiv div.tDiv2 div div span");

		this.getWebDriver()
				.sendKeys(
						"css",
						"#advanced_search  table  tbody  tr:nth-child(2)  td:nth-child(2)  input:nth-child(1)",
						starttime);

		this.getWebDriver()
				.sendKeys(
						"css",
						"#advanced_search  table  tbody  tr:nth-child(2)  td:nth-child(2)  input:nth-child(2)",
						etime);

		this.getWebDriver()
				.findElement("css", "#check_type option:nth-child(3)").click();

		this.getWebDriver().click("id", "searchButton");

		String webtotal = this
				.getWebDriver()
				.getText("css",
						"#delete_form  div  div.pDiv  div.pDiv2  div:nth-child(5)  span span");

		int total = Integer.valueOf(webtotal.trim());
		int flag = 1;
		while (total >= flag) {
			flag++;

			handleElement2Outv(purchases);
			this.getWebDriver()
					.click("css",
							"#delete_form  div  div.pDiv  div.pDiv2  div:nth-child(7)  div.pNext.pButton  span");

		}

		inventoryService.removeInventoryCommon(purchases, map);

		 this.getAssistCatchData().getCata().setOutstore(purchases);
		return true;
	}

	@Override
	public boolean getPayAccountData() throws BusinessException {
		// TODO Auto-generated method stub
		return true;
	}
	@Override
	public BankCardCheck isSupplyAccountCorrect() throws BusinessException {
		BankCardCheck bcc = new BankCardCheck();
		bcc.setCorrect(true);
		
		return bcc;
	}
}
